import BLELocker from '../../common/BLELocker.js';
import CONSTANT_DATA from '../../common/constant_data.js';
import common from '../../common/common.js';
var downloadUtil = require("download.js")
var util = require("util.js");
var colonyBlue = require("../../pages/index/colony_blue.js");
var _driverVersion = null;
var retryGetServiceCount = 2;
var app = getApp();
var curScanMac = null;
var curScanCallback = null;
var notifyRetryCount = 0;
const SERVICE_FEE7_UUID = "0000FEE7-0000-1000-8000-00805F9B34FB";
const CHARACTERIS_FEC7_UUID = "0000FEC7-0000-1000-8000-00805F9B34FB";
const CHARACTERIS_FEC8_UUID = "0000FEC8-0000-1000-8000-00805F9B34FB";

function connectLease(device, scanMac, scanMacCallback) {
  curScanMac = scanMac;
  curScanCallback = scanMacCallback;
  if (app.globalData._that) {
    app.globalData._that.setData({
      loading_show: true,
      loading_desc: '设备开始连接...',
      connectDesc: "设备开始连接...",
    })
  }
  //停止搜索超时定时器
  clearTimeout(app.globalData.scanEquTimer)
  console.log("开始连接----->", device, scanMac, device.deviceId)

  let conTimeoutLen = app.globalData.conRetryTotalCount == app.globalData.conRetryCount ? 5000 : 10000;
  if (app.globalData.isDirectConnect) {
    //直连超时设置3秒
    conTimeoutLen = 3000
  }
  wx.createBLEConnection({
    deviceId: device.deviceId,
    timeout: conTimeoutLen,
    success: function (res) {
      //连接成功的类型
      app.globalData.connectSucType = 'ble'
      conSucHandle(device, scanMac)
    },
    fail: function (err) {
      //停止搜索
      wx.stopBluetoothDevicesDiscovery({
        success(res) {
          console.log(res)
        }
      })
      wx.closeBLEConnection({
        deviceId: device.deviceId,
        success: function (res) {
          console.log("连接关闭成功-fail,", scanMac, res);
        },
        fail: function (err) {
          console.log("关闭失败-fail,", scanMac, err);
        }
      })

      if (scanMac) {
        //移除掉缓存
        let delMac = scanMac.indexOf("DK") == 0 ? scanMac.substring(2) : scanMac;
        wx.removeStorageSync(delMac);
      }
      console.log("连接失败:" + app.globalData.conRetryCount, err); // mark: 蓝牙连接失败
      let errInfo = err ? JSON.stringify(err) : "";
      let devId = device ? device.deviceId : "null";
      util.recordLog(CONSTANT_DATA.err_type.new_con_fail, "连接失败" + app.globalData.conRetryCount + ":" + scanMac + ":" + errInfo + ":" + devId);

      if (app.globalData.isDirectConnect) {//直连判断
        //判断是否为已连接状态
        if (err && err.errno == '1509007' && err.errMsg.indexOf('already connect') != -1) {
          //设备已连接
          conSucHandle(device, scanMac)
          return
        }
        
        util.recordLog(CONSTANT_DATA.err_type.connect_direct_timeout, 'direct connect fail:' + errInfo);
        common.clearConTimeCountTimer('cc-119')
        let defeatCount = wx.getStorageSync('direct_defeat_count')
        defeatCount=defeatCount?defeatCount:0
        //直连底层错误提示1次
        if (err && err.errno == '1509001' && err.errMsg.indexOf('connection fail') != -1 && defeatCount != 1) {
          defeatCount=defeatCount+1
          wx.setStorageSync('direct_defeat_count', defeatCount)
          stopConProcess()
          app.globalData._that.setData({
            loading_show: false,
            modal: {
              modal_show: true,
              desc: '请开关手机蓝牙，扫码重试',
              confirm: true
            }
          });
          return
        }
        wx.removeStorageSync('direct_defeat_count')
        wx.setStorageSync('direct_con_forbidden', 1)//标记不走直连
        //直连,校验权限
        let checkRst = app.globalData._that.bleConAuthCheck(true)
        if (checkRst > 0) {
          //提示用户授权
          console.log('提示用户授权----------》', curScanMac)
          util.recordLog(CONSTANT_DATA.err_type.connect_direct_timeout, '提示用户授权:' + curScanMac);
        } else {
          console.log('正常扫码连接----------》', curScanMac)
          app.globalData._that.data.curIsDirectCon = false
          app.globalData._that.data.leaseShow.resultShow("请开关下蓝牙后重新扫码")          
          util.recordLog(CONSTANT_DATA.err_type.connect_direct_timeout, '提示开关蓝牙重新扫码:' + curScanMac);      
        }
        return
      }

      if (app.globalData.conTimeoutTimer) {
        clearTimeout(app.globalData.conTimeoutTimer);
        app.globalData.conTimeoutTimer = setTimeout(function () {
          if (!app.globalData.conIsSuc) {
            if (!app.globalData.networkIsCon) {
              stopConProcess()
              app.globalData._that.setData({
                loading_show: false,
                modal: {
                  modal_show: true,
                  desc: '连接超时，请关闭蓝牙再打开后重试(Z' + app.globalData.curConHid + ')',
                  confirm: true
                }
              });
            }
            colonyBlue.bleConFailMark();
            wx.closeBLEConnection({
              deviceId: device.deviceId,
              success: function (res) {
                console.log("连接关闭成功,", scanMac, res);
              },
              fail: function (err) {
                console.log("关闭失败,", scanMac, err);
              }
            })
          }
        }, 35000);
      }
      // let conRetryOldConFlg = wx.getStorageSync("conFailRetryOldCon");
      if (app.globalData.conRetryCount > 0) {
        clearTimeout(app.globalData.conTimeoutTimer);
        stopConProcess()
        app.globalData._that.setData({
          loading_show: true,
          loading_desc: '请稍等,重试连接中..' + app.globalData.conRetryCount,
          connectDesc: "重试连接" + app.globalData.conRetryCount,
        })
        app.globalData.conRetryCount = app.globalData.conRetryCount - 1;
        wx.closeBLEConnection({
          deviceId: device.deviceId,
          success: function (res) {
            console.log("连接关闭成功,重新搜索设备连接,", scanMac, res);
            scanMacCallback(scanMac);
          },
          fail: function (err) {
            console.log("关闭失败,重新搜索设备连接,", scanMac, err);
            scanMacCallback(scanMac);
          }
        })

      } else {
        stopConProcess()
        app.globalData._that.setData({
          loading_show: true,
          loading_desc: '请稍等,最后重试连接中...',
          connectDesc: "请稍等,最后重试连接中...",
        })
        if (app.globalData.conTimeoutTimer) {
          clearTimeout(app.globalData.conTimeoutTimer);
        }

        wx.closeBLEConnection({
          deviceId: device.deviceId,
          success: function (res) {
            console.log("连接关闭成功,", scanMac, res);
          },
          fail: function (err) {
            console.log("关闭失败,", scanMac, err);
          }
        })

        wx.setStorageSync("conFailRetryOldCon", true);
        //才使用之前的连接方式进行连接
        let blueStatHandleObj = BLELocker.getParams();
        app.globalData.isDirectConnect = false;
        let blueName = scanMac.indexOf("DK") == 0 ? scanMac : "DK" + scanMac;
        console.log("采用之前的旧连接进行重试", blueStatHandleObj, blueName);
        util.recordLog(CONSTANT_DATA.err_type.new_con_old, "新连接失败,采用旧连接:" + blueName);
        var timebyte = null;
        var encryptval = null;
        BLELocker.newConnect(blueName, blueStatHandleObj.callback, 0, false, encryptval, timebyte, blueStatHandleObj.that);
        colonyBlue.bleConFailMark();
      }

    }
  })
}

//连接成功处理
function conSucHandle(device, scanMac) {
  if (app.globalData.isDirectConnect) {
    //标记此手机可以使用直连方式连接
    wx.setStorageSync('direct_con_suc', 1)
  }

  //连接成功，等待数据接收操作
  app.globalData.isConnecting = false;
  app.globalData.conNoticeTimer = setTimeout(function () {
    if (!app.globalData.conIsSuc) {
      if (app.globalData.conTimeoutTimer) {
        clearTimeout(app.globalData.conTimeoutTimer);
      }
      stopConProcess()
      if (!app.globalData.networkIsCon) {
        app.globalData._that.setData({
          loading_show: false,
          modal: {
            modal_show: true,
            desc: '设备响应超时,请重新扫码(Z' + app.globalData.curConHid + ')',
            confirm: true
          }
        })
      }
      colonyBlue.bleConFailMark();
      wx.closeBLEConnection({
        deviceId: device.deviceId,
        success: function (res) {
          console.log("连接关闭成功,", scanMac, res);
        },
        fail: function (err) {
          console.log("关闭失败,", scanMac, err);
        }
      })
      util.recordLog(CONSTANT_DATA.err_type.new_con_equ_timeout, "连接成功,设备无响应,关闭连接");
    }
  }, 10000);
  app.globalData.beforeConIsGateway = false;
  util.recordLog(CONSTANT_DATA.err_type.ble_create_con_suc, "创建连接成功a");

  app.globalData._that.setData({
    loading_show: true,
    loading_desc: '连接成功,开始读取数据...',
    connectDesc: "连接成功,开始读取数据",
  })
  cacheScanMac(scanMac, device.deviceId);
  app.globalData.conRetryCount = -1;
  BLELocker.setDevice(device);
  //停止搜索
  wx.stopBluetoothDevicesDiscovery({
    success(res) {
      console.log(res)
    }
  })

  notifyRetryCount = 0;
  getSerciceAndNotify(device, 50);
}

function getSerciceAndNotify(device, serviceTimeoutLen) {
  setTimeout(function () {
    wx.getBLEDeviceServices({
      deviceId: device.deviceId,
      success: function (res) {
        console.log("应用服务接口。。", res);
        //获取1530的服务
        for (var i = 0; i < res.services.length; i++) {
          var uuid = res.services[i]["uuid"]
          if (uuid.indexOf("0000FEE7") != -1) {
            console.log("应用服务uuid-->" + uuid);
            device.fee7 = res.services[i];
            notifyRetryCount = 0;
          }
        }
        if (!device.fee7) {
          //使用固定的值进行处理
          console.log("没有获取到服务uuid采用固定值:" + SERVICE_FEE7_UUID);
          util.recordLog(CONSTANT_DATA.err_type.new_conf_uuid_nofound, "用固定服务uuid:" + SERVICE_FEE7_UUID + ":" + app.globalData.isLeaseCon);
          device.fee7 = {
            uuid: SERVICE_FEE7_UUID,
            isPrimary: true
          };
        }
        //获取特征码值并发起通知
        getCharacteristics(device);
      },
      fail: function (err) {
        console.log("获取getBLEDeviceServices失败:" + retryGetServiceCount, err);
        util.recordLog(CONSTANT_DATA.err_type.new_conf_service_fail, "用固定的服务uuid:" + retryGetServiceCount + ":" + app.globalData.isLeaseCon);
        if (app.globalData.conNoticeTimer) {
          clearTimeout(app.globalData.conNoticeTimer);
        }

        device.fee7 = {
          uuid: SERVICE_FEE7_UUID,
          isPrimary: true
        };
        //采用固定值进行获取特征码值
        getCharacteristics(device);

      }
    })
  }, serviceTimeoutLen);
}

function getCharacteristics(device) {
  setTimeout(function () {
    wx.getBLEDeviceCharacteristics({
      deviceId: device.deviceId,
      serviceId: device.fee7["uuid"],
      success: function (res) {
        console.log("获取特征码...", res);
        for (var i in res.characteristics) {
          var c = res.characteristics[i]
          if (c.uuid.indexOf("FEC7") != -1 || c.uuid == "000036F5-0000-1000-8000-00805F9B34FB") {
            device.fec7 = c
            BLELocker.setWriteUuid(c.uuid, device.fee7["uuid"]);
          }
          if (c.uuid.indexOf("FEC8") != -1 || c.uuid == "000036F6-0000-1000-8000-00805F9B34FB") {
            device.fec8 = c
          }
        }
        if (!device.fec7) {
          device.fec7 = {
            uuid: CHARACTERIS_FEC7_UUID
          };
        }
        if (!device.fec8) {
          device.fec8 = {
            uuid: CHARACTERIS_FEC8_UUID
          };
        }
        //发起通知后可以立刻接收到蓝牙返回的数据
        wx.notifyBLECharacteristicValueChange({
          deviceId: device.deviceId,
          serviceId: device.fee7["uuid"],
          characteristicId: device.fec8["uuid"],
          state: true,
          success: function (res) {
            console.log("发送通知成功...", res);
            callback(device);

            if (app.globalData.conNoticeTimer) {
              clearTimeout(app.globalData.conNoticeTimer);
            }
          },
          fail: function (err) {

          },
          complete: function (res) {
            if (device.fec7 && device.fec7.uuid == "000036F5-0000-1000-8000-00805F9B34FB") {
              console.log("陪护椅发送获取token")
              setTimeout(function () {
                bleGetToken();
              }, 1200);
            }
          }
        })
      },
      fail: function (err) { // mark: 获取特征码失败a
        console.log("获取特征码失败", err);
        let errInfo = err ? JSON.stringify(err) : "null";
        util.recordLog(CONSTANT_DATA.err_type.new_conf_char_fail, "获取特征码失败:" + errInfo + ":" + app.globalData.isLeaseCon);
        if (app.globalData.conNoticeTimer) {
          clearTimeout(app.globalData.conNoticeTimer);
        }
        if (app.globalData.conTimeoutTimer) {
          clearTimeout(app.globalData.conTimeoutTimer);
        }
        //发起通知后可以立刻接收到蓝牙返回的数据
        wx.notifyBLECharacteristicValueChange({
          deviceId: device.deviceId,
          serviceId: CHARACTERIS_FEC7_UUID,
          characteristicId: CHARACTERIS_FEC8_UUID,
          state: true,
          success: function (res) {
            console.log("发送通知成功...", res);
            callback(device);

            if (app.globalData.conNoticeTimer) {
              clearTimeout(app.globalData.conNoticeTimer);
            }
          },
          fail: function (err) {
            //关闭连接，关闭适配器
            console.log("发送通知失败...", err);
            wx.closeBLEConnection({
              deviceId: device.deviceId,
              success: function (res) {},
              complete: function () {
                wx.closeBluetoothAdapter({
                  success: function (res) {},
                })
              }
            })
            if (!app.globalData.conIsSuc && app.globalData._that) {
              // mark: 获取特征码失败提示
              if (!app.globalData.networkIsCon) {
                stopConProcess()
                //非网络断开提示蓝牙异常信息
                app.globalData._that.setData({
                  loading_show: false,
                  modal: {
                    modal_show: true,
                    desc: '获取特征码失败,请重新扫码(Z' + app.globalData.curConHid + ')',
                    confirm: true
                  }
                })
              }
            } else {
              wx.showModal({
                title: '温馨提示',
                content: '获取特征码失败,请重新扫码(Z' + app.globalData.curConHid + ')'
              })
            }
          }
        })
      }
    })
  }, 50)
}
// mark: 停止独立连接页面的连接进程
function stopConProcess() {
  if (app.globalData._that) {
    if (typeof app.globalData._that.cleanTimer == 'function') {
      app.globalData._that.cleanTimer()
    }
    if (typeof app.globalData._that.cleanTimer == 'function') {
      app.globalData._that.hideAllShow()
    }
  }

}

//收到固件传来的信息处理，开启notify后，向1531写入信息后，固件会传回信息
function callback(device) {
  BLELocker.statusChanged(BLELocker.Status.bleReceiveData);
  wx.onBLECharacteristicValueChange(function (res) {
    let hexValue = util.hexFromBuffer(res.value).toUpperCase(); //将信息转为16进制
    console.log("返回的数据:" + hexValue);
    BLELocker.handleDeviceData(hexValue.toUpperCase(), device, res);
  })
}

//缓存
function cacheScanMac(mac, deviceId) {
  if (mac && mac.indexOf("DK") == 0) {
    let sMac = mac.substring(2);
    let device = {
      "deviceId": deviceId
    };
    wx.setStorageSync(sMac, device);
  }
}

/**
 * 获取陪护椅的token
 */
function bleGetToken() {
  console.log("bleGetToken");
  for (var e = app, a = 0; a < e.globalData.bleVariable.cmds.getTokenCmd.length; a++) a <= 3 || (e.globalData.bleVariable.cmds.getTokenCmd[a] = Math.round(100 * Math.random()));
  BLELocker.sendPeiHuYiBleGetToken(
    function (isSuccess) {
      if (isSuccess == false) {
        util.recordLog(CONSTANT_DATA.err_type.data_peihuyi_token_send_fail, "陪护椅token发送失败")
      } else {
        util.recordLog(CONSTANT_DATA.err_type.data_peihuyi_token_send_suc, "陪护椅token发送成功")
      }
    }
  );
}


module.exports = {
  connectLease: connectLease,
  getSerciceAndNotify: getSerciceAndNotify
}